<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
    @selection-change：多选按钮改变事件
    -->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope"><!--scope里面有整行数据-->
          <span style="color: green" v-if="scope.row.state == 1">启用</span>
          <span style="color: red" v-else-if="scope.row.state == 0">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <!--
      scope.$index: 当前列的索引
      scope.row：当前行的数据
      -->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <!--表示这个删除按钮需要当前用户持有department:delete这个权限才能显示-->
          <el-button type="danger" v-perm="'department:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

   <!-- /*主键id*/
    /*部门编号*/
    private String sn;
    /*部门名称*/
    private String name;
    /*部门状态*/
    private Integer state;

    /*关联的部门经理*/
    private Employee manager;

    /*上级部门*/
    private Department parent;-->
		<!--编辑界面-->
    <!--:rules表单校验规则
    ref="editForm" 给表单取了一个引用名字
    -->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

        <!--下午做-->
        <el-form-item label="部门经理">
<!--          <el-input v-model="editForm.manager" auto-complete="off"></el-input>-->

          <!--elementUI提供的单选下拉框
            :key -对象的唯一标识
            :label -选择某个选项以后显示在输入框中的值
            :value -要传到后端的值 employee就是一个对象  后端manager又正好是一个对象
          -->
          <el-select clearable v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.username"
                :value="employee">
              <span style="float: left">{{ employee.username }}</span><!--下拉选项左边显示的-->
              <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.phone }}</span><!--下拉选项右边显示的-->
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="上级部门">
<!--          <el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
          <!--ElementUI提供的级联选择器
          :options  绑定的部门数组
          -->
          <el-cascader v-model="editForm.parent"
              :options="treeDepartments"
              :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }"
              clearable></el-cascader>
        </el-form-item>


			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
			  treeDepartments:[],
			  employees:[],
        title:"",
				filters: {
					keyword: ''
				},
				departments: [],
				total: 0,
				currentPage: 1,
        pageSize:5,
				listLoading: false,
				sels: [],//列表选中行

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' },//name的校验规则：在输入框失去焦点的时候触发校验 这个规则是不能为空
            { min: 2, max: 4, message: '长度在 3 到 5 个字符', trigger: 'blur' }
					],
          sn:[
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ]
				},
				//编辑或新增界面数据
				editForm: {
					id: null,
					name: '',
          sn:'',//部门编号
					state: 1,//状态
          manager:null,//部门经理
          parent:null//父级部门
				}
			}
		},
		methods: {
		  /*关键字搜索处理方法*/
      search(){
      //  把当前页置为第一页
        //调用获取数据的方法
        this.currentPage = 1;
        this.getDepartments();
      },

			//性别显示转换
			formatState: function (row, column) {
				return row.state == 1 ? '<span style="color: green">启用</span>' : row.state == 0 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.currentPage,
          pageSize:this.pageSize,
					keyword: this.filters.keyword
				};
				//开启页面忙等
				this.listLoading = true;
				/*请求后端分页数据*/
        this.$http.post("/dept",para).
        then(res=>{//处理请求成功的回调函数
          //开启页面忙等
          this.listLoading = false;
          this.departments = res.data.list;
          this.total = res.data.total;
        }).catch(res=>{//处理请求失败的回调函数
          this.$message.error("网络异常");
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {//当你点击确认以后的处理逻辑
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/dept/"+row.id).then(res=>{
            if (res.data.success){//后台返回成功
              this.$message.success(res.data.message);
            }else {//后台返回失败
              this.$message.error(res.data.message);//后台返回失败 数据库不一定真的删除失败
            }
            this.currentPage = 1;
            this.getDepartments();//1.跳到上一页 2.定位到第一页
          }).catch(res=>{
            this.$message.error("网络异常")
          })

				}).catch(() => {//当你点击取消以后的处理逻辑 这儿都不做

				});
			},
			//显示编辑界面 ctrl+f12 显示骨架
			handleEdit: function (index, row) {
        this.getTree();
        if (this.$refs['editForm']) {
          this.$refs['editForm'].resetFields();//取消表单校验提示
        }

        this.title = "编辑";
				this.editFormVisible = true;//显示对话框

				this.editForm = Object.assign({}, row);//对象克隆 回显数据
        if (row.parent) {
          let dirPath = row.dirPath;// /79/56/80==>[79,56]
          let dirPathArr = dirPath.split("/");
          let dirPathResult = [];
          for (let i = 1; i < dirPathArr.length - 1; i++) {
            dirPathResult.push(parseInt(dirPathArr[i]));//parseInt()将字符串类型的数字 转成数字类型
          }
          this.editForm.parent = dirPathResult;
        }

			},
			//显示新增界面
			handleAdd: function () {
        this.getTree();
        if (this.$refs['editForm']) {
          this.$refs['editForm'].resetFields();//取消表单校验提示
        }
        this.title = "新增";
        this.editFormVisible = true;
				this.editForm = {//表单置空
          id: null,
          name: '',
          sn:'',//部门编号
          state: 1,//状态
          manager:null,//部门经理
          parent:null//父级部门
				};
			},
			//编辑
      /*
      * this.$refs.editForm.validate（） 获取到指定表单editForm 然后主动发起校验
      * */
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);//克隆
              //处理提交的数据 todo
              let parentArr = para.parent;
              if(parentArr) {//如果选择了父部门 才走下面的逻辑
                let parent = {id: parentArr[parentArr.length - 1]}//后端的department实体中需要一个parent对象
                para.parent = parent
              }
              /*提交表单*/
              this.$http.put("/dept",para).then(res=>{
                this.editLoading = false;//关闭提交按钮忙等

                if (res.data.success){//后台返回成功
                  this.editFormVisible = false;//关闭弹窗
                  this.$message.success(res.data.message);
                }else {//后台返回失败
                  this.$message.error(res.data.message);//后台返回失败 数据库不一定真的删除失败
                }
                this.currentPage = 1;
                this.getDepartments();//1.跳到上一页 2.定位到第一页
              }).catch(res=>{
                this.editLoading = false;//关闭提交按钮忙等
                this.$message.error("网络异常")
              })

							/*editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},
			//新增
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        /*把选中行数组对象 转换成 取每个对象里面的id 转成id数组  [1,5,6,7]*/
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					/*发起删除请求*/
          this.$http.patch("/dept",ids).then(res=>{

            if (res.data.success){//后台返回成功
              this.$message.success(res.data.message);
            }else {//后台返回失败
              this.$message.error(res.data.message);//后台返回失败 数据库不一定真的删除失败
            }
            this.currentPage = 1;
            this.getDepartments();//1.跳到上一页 2.定位到第一页
          }).catch(res=>{
            this.$message.error("网络异常");
          })

				}).catch(() => {

				});
			},
      getEmployees(){//获取所有员工
			  this.$http.get("/employee").then(res=>{
			    this.employees = res.data
        }).catch(res=>{
          this.$message.error("查询所有员工失败")
        })
      },
      getTree(){//获取部门树的方法
        this.$http.get("/dept/getTree").then(res=>{
          this.treeDepartments = res.data
        }).catch(res=>{
          this.$message.error("查询部门树失败")
        })
      }

		},
		mounted() {
			this.getDepartments();
			this.getEmployees();//为了性能考虑 我们在页面加载完成就获取所有员工
		}
	}

</script>

<style scoped>

</style>